package me.zxk.smartagriculture.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zxk.smartagriculture.common.ErrorCode;
import me.zxk.smartagriculture.dto.user.*;
import me.zxk.smartagriculture.entity.User;
import me.zxk.smartagriculture.entity.UserSettings;
import me.zxk.smartagriculture.repository.UserRepository;
import me.zxk.smartagriculture.repository.UserSettingsRepository;
import me.zxk.smartagriculture.util.PasswordUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 用户服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserService {

    private final UserRepository userRepository;
    private final UserSettingsRepository userSettingsRepository;

    /**
     * 获取用户信息
     */
    public UserInfoResponse getUserInfo(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException(ErrorCode.USER_NOT_FOUND.getMessage()));

        UserInfoResponse response = new UserInfoResponse();
        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setNickname(user.getNickname());
        response.setAvatarUrl(user.getAvatarUrl());
        response.setPhone(user.getPhone());
        response.setEmail(user.getEmail());
        response.setLevel(user.getLevel());
        response.setExperience(user.getExperience());

        // 设置农业统计数据
        UserInfoResponse.FarmStats farmStats = new UserInfoResponse.FarmStats(
                user.getTotalArea(), user.getCropCount(), user.getHarvestCount());
        response.setFarmStats(farmStats);

        return response;
    }

    /**
     * 更新用户信息
     */
    @Transactional
    public UserInfoResponse updateUserInfo(Long userId, UpdateUserRequest request) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException(ErrorCode.USER_NOT_FOUND.getMessage()));

        // 检查手机号是否已被其他用户使用
        if (StringUtils.hasText(request.getPhone()) && !request.getPhone().equals(user.getPhone())) {
            if (userRepository.existsByPhone(request.getPhone())) {
                throw new RuntimeException(ErrorCode.PHONE_EXISTS.getMessage());
            }
        }

        // 检查邮箱是否已被其他用户使用
        if (StringUtils.hasText(request.getEmail()) && !request.getEmail().equals(user.getEmail())) {
            if (userRepository.existsByEmail(request.getEmail())) {
                throw new RuntimeException(ErrorCode.EMAIL_EXISTS.getMessage());
            }
        }

        // 更新用户信息
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }

        userRepository.save(user);
        log.info("用户信息更新成功: {}", userId);

        return getUserInfo(userId);
    }

    /**
     * 修改密码
     */
    @Transactional
    public void changePassword(Long userId, ChangePasswordRequest request) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException(ErrorCode.USER_NOT_FOUND.getMessage()));

        // 验证当前密码
        if (!PasswordUtil.matches(request.getCurrentPasswordMd5(), user.getPasswordMd5())) {
            throw new RuntimeException(ErrorCode.PASSWORD_ERROR.getMessage());
        }

        // 更新密码
        user.setPasswordMd5(PasswordUtil.encode(request.getNewPasswordMd5()));
        userRepository.save(user);

        log.info("用户密码修改成功: {}", userId);
    }

    /**
     * 更新用户头像URL
     */
    @Transactional
    public void updateUserAvatar(Long userId, String avatarUrl) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException(ErrorCode.USER_NOT_FOUND.getMessage()));

        user.setAvatarUrl(avatarUrl);
        userRepository.save(user);
        log.info("用户头像更新成功: userId={}, avatarUrl={}", userId, avatarUrl);
    }

    /**
     * 删除用户账户
     */
    @Transactional
    public void deleteUser(Long userId) {
        if (!userRepository.existsById(userId)) {
            throw new RuntimeException(ErrorCode.USER_NOT_FOUND.getMessage());
        }

        userRepository.deleteById(userId);
        log.info("用户账户删除成功: {}", userId);
    }

    /**
     * 获取用户设置
     */
    public UserSettingsResponse getUserSettings(Long userId) {
        UserSettings settings = userSettingsRepository.findByUserId(userId)
                .orElse(createDefaultSettings(userId));

        return new UserSettingsResponse(settings.getUserId(),
                settings.getDarkModeEnabled(), settings.getNotificationsEnabled());
    }

    /**
     * 更新用户设置
     */
    @Transactional
    public UserSettingsResponse updateUserSettings(Long userId, UpdateUserSettingsRequest request) {
        UserSettings settings = userSettingsRepository.findByUserId(userId)
                .orElse(createDefaultSettings(userId));

        if (request.getDarkModeEnabled() != null) {
            settings.setDarkModeEnabled(request.getDarkModeEnabled());
        }
        if (request.getNotificationsEnabled() != null) {
            settings.setNotificationsEnabled(request.getNotificationsEnabled());
        }

        userSettingsRepository.save(settings);
        log.info("用户设置更新成功: {}", userId);

        return new UserSettingsResponse(settings.getUserId(),
                settings.getDarkModeEnabled(), settings.getNotificationsEnabled());
    }

    /**
     * 创建默认用户设置
     */
    private UserSettings createDefaultSettings(Long userId) {
        UserSettings settings = new UserSettings();
        settings.setUserId(userId);
        settings.setDarkModeEnabled(false);
        settings.setNotificationsEnabled(true);
        return userSettingsRepository.save(settings);
    }
}
